<?php
/**
 * Created by PhpStorm.
 * User: yangwang
 * Date: 2024-04-28
 * Time: 16:03
 */

namespace App\Http\Controllers\Cruise\Web;


use App\Enums\BaseErrorCode;
use App\Exports\Cruise\ShopLicenseExport;
use App\Exports\WorkOrder\FunctionOpenExport;
use App\Http\Controllers\BaseController;
use App\Jobs\Export\Export;
use App\Models\Cruise\CruiseShopLicenseRecordsModel;
use App\Service\Cruise\Shop\CruiseShopLicenseRecordsLogService;
use App\Service\Cruise\Shop\CruiseShopLicenseRecordsService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class CruiseShopLicenseController extends BaseController
{
    public function list(Request $request)
    {
        $pageSize               = (int)$request->get('pageSize', 10);
        $pageNum                = (int)$request->get('pageNum', 1);
        $shopIds                = $request->get('shopIds', '');
        $dimCode                = $request->get('dimCode', '');
        $shopStatus             = $request->get('shopStatus', '');
        $status                 = $request->get('status', '');
        $councilorId            = $request->get('councilorId', 0);
        $merchantUpdatedAtStart = $request->get('merchantUpdatedAtStart', '');
        $merchantUpdatedAtEnd   = $request->get('merchantUpdatedAtEnd', '');
        $cruiseAtStart          = $request->get('cruiseAtStart', '');
        $cruiseAtEnd            = $request->get('cruiseAtEnd', '');
        $activityDays           = $request->get('activityDays', 0);
        $sortField              = $request->get('sortField', '');
        $sortOrder              = $request->get('sortOrder', '');
        $export                 = (bool)$request->get('export', false);

        $orderBy = [];
        if ($sortField && $sortOrder) {
            $orderMap = [
                'ascend'  => 'asc',
                'descend' => 'desc'
            ];
            $order    = $orderMap[$sortOrder] ?? '';
            if (empty($order)) {
                return $this->fail(BaseErrorCode::$BASE_CODE_LIST_FAIL, '排序字段异常');
            }
            $orderBy = [$sortField => $order];
        }

        if ($export) {

            $fileName = vsprintf("%s_%s", [
                '门店证件备案',
                date("Y_m_d_H_i_s", time())
            ]);
            $data     = [
                'pageSize'               => $pageSize,
                'pageNum'                => $pageNum,
                'shopIds'                => $shopIds,
                'dimCode'                => $dimCode,
                'shopStatus'             => $shopStatus,
                'status'                 => $status,
                'councilorId'            => $councilorId,
                'merchantUpdatedAtStart' => $merchantUpdatedAtStart,
                'merchantUpdatedAtEnd'   => $merchantUpdatedAtEnd,
                'cruiseAtStart'          => $cruiseAtStart,
                'cruiseAtEnd'            => $cruiseAtEnd,
                'activityDays'           => $activityDays,
                'sortField'              => $sortField,
                'sortOrder'              => $sortOrder,
                'export'                 => $export,
            ];
            dispatch(
                (new Export(
                    $fileName, Export::TYPE_SHOP_LICENSE_RECORDS_LIST, [
                        'data'   => $data,
                        'userId' => $request->user()->id,
                    ]
                ))
            )->onQueue(Export::QUEUE_NAME);
            return $this->success([]);
//            return $this->success(excelDownload(new ShopLicenseExport($data['list']), "执照备案"));
        }

        return $this->success(CruiseShopLicenseRecordsService::list(
            $pageSize, $pageNum, $shopIds, $dimCode, $shopStatus, $status, $councilorId, $merchantUpdatedAtStart,
            $merchantUpdatedAtEnd,
            $cruiseAtStart, $cruiseAtEnd, $activityDays,$orderBy, $export
        ));
    }

    public function info(Request $request)
    {
        $shopId = (int)$request->get('shopId');

        if (empty($shopId)){
            return $this->fail(BaseErrorCode::$BASE_CODE_DETAIL_FAIL, '没有下一个了');
        }

        return $this->success(CruiseShopLicenseRecordsService::cruiseInfo($shopId));
    }

    public function update(Request $request)
    {
        $uid    = request()->user()->id;

        $input = $request->all();

        $validator = Validator::make($input, [
            'shopId'                                  => 'required|integer',
            'businessLicense.id'                      => 'integer',
            'businessLicense.url'                     => 'required|string',
            'businessLicense.licenceNumber'           => 'string',
            'businessLicense.name'                    => 'required|string',
            'businessLicense.licenseEndDate'          => 'string',
            'businessLicense.licenseEndDateIsForever' => 'required|integer',
            'businessLicense.businessScope'           => 'string',
            'businessLicense.ocrResult'               => 'array',

            'foodLicense.id'                      => 'integer',
            'foodLicense.url'                     => 'required|string',
            'foodLicense.licenceNumber'           => 'string',
            'foodLicense.name'                    => 'required|string',
            'foodLicense.licenseEndDate'          => 'string',
            'foodLicense.licenseEndDateIsForever' => 'required|integer',
            'foodLicense.mainBusiness'            => 'required|string',
            'foodLicense.businessScope'           => 'required|string',
            'foodLicense.ocrResult'               => 'array',
        ], [
            'shop.required'                                    => "shopId不能为空",
            'businessLicense.url.required'                     => "营业执照不能为空",
//            'businessLicense.licenceNumber.required'           => "营业执照编号不能为空",
            'businessLicense.name.required'                    => "营业执照名称不能为空",
            'businessLicense.licenseEndDateIsForever.required' => "营业执照是否过期不能为空",

            'foodLicense.url.required'                     => "食品经营许可证不能为空",
//            'foodLicense.licenceNumber.required'           => "食品经营许可证编号不能为空",
            'foodLicense.name.required'                    => "食品经营许可证名称不能为空",
            'foodLicense.mainBusiness.required'            => "食品经营许可证主体业态不能为空",
            'foodLicense.businessScope.required'            => "食品经营许可证主体业态不能为空",
            'foodLicense.licenseEndDateIsForever.required' => "食品经营许可证是否过期不能为空",
        ]);

        if ($validator->fails()) {
            return $this->fail(BaseErrorCode::$BASE_CODE_UPDATE_FAIL, join(';', $validator->errors()->all()));
        }

        $error = [];
        if (!$input['businessLicense']['licenseEndDateIsForever'] && empty($input['businessLicense']['licenseEndDate'])){
            $error[] = '营业执照时间过期时间必填';
        }
        if (!$input['foodLicense']['licenseEndDateIsForever'] && empty($input['foodLicense']['licenseEndDate'])){
            $error[] = '食品经营许可证过期时间必填';
        }

        if ($error){
            return $this->fail(BaseErrorCode::$BASE_CODE_UPDATE_FAIL, join(';', $error));
        }

        CruiseShopLicenseRecordsService::update(
            $uid, $input['shopId'], $input['businessLicense'], $input['foodLicense'],true
        );

        return $this->success();
    }


    public function submit(Request $request): JsonResponse
    {
        $optUserId = request()->user()->id;

        $input     = $request->all();

        $validator = Validator::make($input, [
            'shopId'                           => 'required|integer',
            'businessLicense.id'               => 'required|integer',
            'businessLicense.causeOfRejection' => 'string',
            'businessLicense.remark'           => 'string',
            'businessLicense.auditStatus'      => 'required|integer|in:' . join(',',
                    [CruiseShopLicenseRecordsModel::STATUS_APPROVED, CruiseShopLicenseRecordsModel::STATUS_REJECT]
                ),

            'foodLicense.id'               => 'required|integer',
            'foodLicense.causeOfRejection' => 'string',
            'foodLicense.remark'           => 'string',
            'foodLicense.auditStatus'      => 'required|integer|in:' . join(',',
                    [CruiseShopLicenseRecordsModel::STATUS_APPROVED, CruiseShopLicenseRecordsModel::STATUS_REJECT]
                ),
        ], [
            'businessLicense.id.required'          => "营业执照id异常",
            'businessLicense.auditStatus.required' => "营业执照请审核",
            'foodLicense.id.required'              => "食品经营许可证id异常",
            'foodLicense.auditStatus.required'     => "食品经营许可证请审核",
        ]);

        if ($validator->fails()) {
            return $this->fail(BaseErrorCode::$BASE_CODE_UPDATE_FAIL, join(';', $validator->errors()->all()));
        }

        return $this->success(CruiseShopLicenseRecordsService::cruiseSubmit(
            $optUserId, $input['shopId'], $input['businessLicense'], $input['foodLicense']
        ));
    }


    public function recordLog(Request $request): JsonResponse
    {
        $shopId   = (int)$request->get('shopId');
        $pageSize = (int)$request->get('pageSize', 10);
        $pageNum  = (int)$request->get('pageNum', 1);

        return $this->success(CruiseShopLicenseRecordsLogService::getRecordLog($shopId, $pageSize, $pageNum));
    }


}